package com.dekarrin.util;

/**
 * Handles String padding and centering.
 */
public class StringPadder {
	
	/**
	 * Amount to pad to.
	 */
	private int desiredWidth;
	
	/**
	 * String to use as padding.
	 */
	private String padding;
	
	/**
	 * Creates a new StringPadder.
	 *
	 * @param desiredWidth
	 * Amount to pad to.
	 *
	 * @param padding
	 * String to use as padding. If this is not one character, it may cause a
	 * padded string to end up longer than the specified width.
	 */
	public StringPadder(int desiredWidth, String padding) {
		this.desiredWidth = desiredWidth;
		this.padding = padding;
	}
	
	public int getPaddedLength() {
		return desiredWidth;
	}
	
	public String getPadding() {
		return padding;
	}
	
	/**
	 * Pads a String to the left.
	 *
	 * @param input
	 * The String to pad.
	 *
	 * @return
	 * The padded String.
	 */
	public String padLeft(String input) {
		StringBuilder builder = new StringBuilder(input);
		while (builder.length() < desiredWidth) {
			builder.insert(0, padding);
		}
		return builder.toString();
	}
	
	/**
	 * Pads a String to the right.
	 *
	 * @param input
	 * The String to pad.
	 *
	 * @return
	 * The padded String.
	 */
	public String padRight(String input) {
		StringBuilder builder = new StringBuilder(input);
		while (builder.length() < desiredWidth) {
			builder.append(padding);
		}
		return builder.toString();
	}
	
	/**
	 * Pads a String on both side. The padding starts on the left, so unequal
	 * will, if anything, result in the given text being one character too far
	 * to the right.
	 *
	 * @param input
	 * The String to pad.
	 *
	 * @return
	 * The padded String.
	 */
	public String center(String input) {
		StringBuilder builder = new StringBuilder(input);
		boolean onLeft = true;
		while (builder.length() < desiredWidth) {
			if (onLeft) {
				builder.insert(0, padding);
			} else {
				builder.append(padding);
			}
			onLeft = !onLeft;
		}
		return builder.toString();
	}

}